// 接单逻辑处理操作界面的JavaScript逻辑
class OrderAcceptanceManager {
    constructor() {
        this.ws = null;
        this.orders = [];
        this.filteredOrders = [];
        this.selectedOrders = new Set();
        this.autoRefreshInterval = null;
        this.isAutoRefresh = false;
        this.currentUser = null;
        this.stats = {
            totalOrders: 0,
            pendingAcceptOrders: 0,
            acceptedOrders: 0,
            processingOrders: 0,
            completedOrders: 0,
            todayRevenue: 0
        };
        
        this.init();
    }
    
    init() {
        this.setupEventListeners();
        this.connectWebSocket();
        this.loadUserInfo();
        this.loadOrders();
    }
    
    setupEventListeners() {
        // 筛选器事件
        document.getElementById('statusFilter').addEventListener('change', () => this.filterOrders());
        document.getElementById('priorityFilter').addEventListener('change', () => this.filterOrders());
        document.getElementById('searchInput').addEventListener('input', () => this.filterOrders());
        
        // 窗口关闭时清理
        window.addEventListener('beforeunload', () => {
            if (this.ws) {
                this.ws.close();
            }
        });
    }
    
    connectWebSocket() {
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        // 添加用户ID参数
        const userId = this.currentUser ? this.currentUser.id : 'operator_001';
        const wsUrl = `${protocol}//${window.location.host}/ws?user_id=${userId}`;
        
        this.ws = new WebSocket(wsUrl);
        
        this.ws.onopen = () => {
            this.updateConnectionStatus(true);
            console.log('WebSocket连接已建立');
        };
        
        this.ws.onmessage = (event) => {
            try {
                const message = JSON.parse(event.data);
                this.handleWebSocketMessage(message);
            } catch (error) {
                console.error('解析WebSocket消息失败:', error);
            }
        };
        
        this.ws.onclose = () => {
            this.updateConnectionStatus(false);
            console.log('WebSocket连接已关闭，尝试重连...');
            setTimeout(() => this.connectWebSocket(), 3000);
        };
        
        this.ws.onerror = (error) => {
            console.error('WebSocket错误:', error);
            this.updateConnectionStatus(false);
        };
    }
    
    handleWebSocketMessage(message) {
        switch (message.type) {
            case 'order_created':
                this.handleOrderCreated(message.data);
                break;
            case 'order_status_change':
                this.handleOrderStatusChange(message.data);
                break;
            case 'payment_update':
                this.handlePaymentUpdate(message.data);
                break;
            case 'order_update':
                this.handleOrderUpdate(message.data);
                break;
        }
    }
    
    handleOrderCreated(orderData) {
        // 新订单创建，添加到列表顶部
        this.orders.unshift(orderData);
        this.updateStats();
        this.filterOrders();
        this.showNotification('新订单', `订单 ${orderData.order_no} 已创建`, 'info');
    }
    
    handleOrderStatusChange(statusData) {
        // 订单状态变更
        const orderIndex = this.orders.findIndex(order => order.order_id === statusData.order_id);
        if (orderIndex !== -1) {
            this.orders[orderIndex].order_status = statusData.new_status;
            this.orders[orderIndex].updated_at = statusData.updated_at;
            this.updateStats();
            this.filterOrders();
            this.showNotification('状态变更', `订单 ${statusData.order_no} 状态已更新`, 'warning');
        }
    }
    
    handlePaymentUpdate(paymentData) {
        // 支付状态更新
        const orderIndex = this.orders.findIndex(order => order.order_id === paymentData.order_id);
        if (orderIndex !== -1) {
            this.orders[orderIndex].payment_status = paymentData.payment_status;
            this.orders[orderIndex].paid_amount = paymentData.paid_amount;
            this.orders[orderIndex].updated_at = paymentData.updated_at;
            this.updateStats();
            this.filterOrders();
            this.showNotification('支付更新', `订单 ${paymentData.order_no} 支付状态已更新`, 'success');
        }
    }
    
    handleOrderUpdate(orderData) {
        // 订单信息更新
        const orderIndex = this.orders.findIndex(order => order.order_id === orderData.order_id);
        if (orderIndex !== -1) {
            this.orders[orderIndex] = { ...this.orders[orderIndex], ...orderData };
            this.updateStats();
            this.filterOrders();
        }
    }
    
    loadUserInfo() {
        // 从localStorage或API获取当前用户信息
        this.currentUser = {
            id: localStorage.getItem('user_id') || 'operator_001',
            name: localStorage.getItem('user_name') || '操作员',
            role: localStorage.getItem('user_role') || 'operator'
        };
    }
    
    async loadOrders() {
        try {
            // 模拟API调用
            const response = await fetch('/api/v1/orders/pending');
            const data = await response.json();
            
            if (data.code === 200) {
                this.orders = data.data.orders || [];
                this.updateStats();
                this.filterOrders();
            }
        } catch (error) {
            console.error('加载订单失败:', error);
            // 使用模拟数据
            this.loadMockOrders();
        }
    }
    
    loadMockOrders() {
        // 模拟订单数据
        this.orders = [
            {
                order_id: 1,
                order_no: 'ORD000001',
                order_status: 1,
                payment_status: 1,
                total_amount: 2000,
                paid_amount: 0,
                tenant_id: 'tenant_001',
                landlord_id: 'landlord_001',
                created_at: new Date().toISOString(),
                updated_at: new Date().toISOString(),
                priority: 'high',
                tenant_name: '张三',
                landlord_name: '李四',
                property_address: '北京市朝阳区xxx小区'
            },
            {
                order_id: 2,
                order_no: 'ORD000002',
                order_status: 1,
                payment_status: 1,
                total_amount: 1500,
                paid_amount: 0,
                tenant_id: 'tenant_002',
                landlord_id: 'landlord_002',
                created_at: new Date(Date.now() - 300000).toISOString(),
                updated_at: new Date(Date.now() - 300000).toISOString(),
                priority: 'medium',
                tenant_name: '王五',
                landlord_name: '赵六',
                property_address: '上海市浦东新区xxx公寓'
            }
        ];
        this.updateStats();
        this.filterOrders();
    }
    
    updateStats() {
        this.stats.totalOrders = this.orders.length;
        this.stats.pendingAcceptOrders = this.orders.filter(order => order.order_status === 1).length;
        this.stats.acceptedOrders = this.orders.filter(order => order.order_status === 2).length;
        this.stats.processingOrders = this.orders.filter(order => order.order_status === 3).length;
        this.stats.completedOrders = this.orders.filter(order => order.order_status === 4).length;
        this.stats.todayRevenue = this.orders
            .filter(order => order.payment_status === 2)
            .reduce((sum, order) => sum + order.paid_amount, 0);
        
        this.updateStatsDisplay();
    }
    
    updateStatsDisplay() {
        document.getElementById('totalOrders').textContent = this.stats.totalOrders;
        document.getElementById('pendingAcceptOrders').textContent = this.stats.pendingAcceptOrders;
        document.getElementById('acceptedOrders').textContent = this.stats.acceptedOrders;
        document.getElementById('processingOrders').textContent = this.stats.processingOrders;
        document.getElementById('completedOrders').textContent = this.stats.completedOrders;
        document.getElementById('todayRevenue').textContent = `¥${this.stats.todayRevenue.toFixed(2)}`;
    }
    
    filterOrders() {
        const statusFilter = document.getElementById('statusFilter').value;
        const priorityFilter = document.getElementById('priorityFilter').value;
        const searchTerm = document.getElementById('searchInput').value.toLowerCase();
        
        this.filteredOrders = this.orders.filter(order => {
            const statusMatch = !statusFilter || order.order_status.toString() === statusFilter;
            const priorityMatch = !priorityFilter || order.priority === priorityFilter;
            const searchMatch = !searchTerm || 
                order.order_no.toLowerCase().includes(searchTerm) ||
                (order.tenant_name && order.tenant_name.toLowerCase().includes(searchTerm)) ||
                (order.landlord_name && order.landlord_name.toLowerCase().includes(searchTerm));
            
            return statusMatch && priorityMatch && searchMatch;
        });
        
        this.renderOrders();
    }
    
    renderOrders() {
        const ordersList = document.getElementById('ordersList');
        
        if (this.filteredOrders.length === 0) {
            ordersList.innerHTML = `
                <div class="text-center py-4">
                    <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                    <p class="text-muted">暂无符合条件的订单</p>
                </div>
            `;
            return;
        }
        
        const ordersHtml = this.filteredOrders.map(order => this.renderOrderCard(order)).join('');
        ordersList.innerHTML = ordersHtml;
    }
    
    renderOrderCard(order) {
        const statusClass = this.getStatusClass(order.order_status);
        const priorityClass = this.getPriorityClass(order.priority);
        const timeAgo = this.getTimeAgo(order.created_at);
        
        return `
            <div class="card order-card ${statusClass}" data-order-id="${order.order_id}">
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-1">
                            <div class="order-priority ${priorityClass}">
                                ${order.priority === 'high' ? 'H' : order.priority === 'medium' ? 'M' : 'L'}
                            </div>
                        </div>
                        <div class="col-md-2">
                            <h6 class="mb-1">${order.order_no}</h6>
                            <small class="order-timer">${timeAgo}</small>
                        </div>
                        <div class="col-md-2">
                            <div class="tenant-info">
                                <div class="user-avatar">${order.tenant_name ? order.tenant_name.charAt(0) : 'T'}</div>
                                <div>
                                    <div class="fw-bold">${order.tenant_name || '租客'}</div>
                                    <small class="text-muted">租客</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="landlord-info">
                                <div class="user-avatar">${order.landlord_name ? order.landlord_name.charAt(0) : 'L'}</div>
                                <div>
                                    <div class="fw-bold">${order.landlord_name || '房东'}</div>
                                    <small class="text-muted">房东</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="order-amount">¥${order.total_amount}</div>
                            <small class="text-muted">总金额</small>
                        </div>
                        <div class="col-md-1">
                            <span class="badge status-${statusClass}">${this.getStatusText(order.order_status)}</span>
                            <br>
                            <span class="badge payment-status-${this.getPaymentStatusClass(order.payment_status)}">
                                ${this.getPaymentStatusText(order.payment_status)}
                            </span>
                        </div>
                        <div class="col-md-2">
                            <div class="action-buttons">
                                <button class="btn btn-success btn-sm" onclick="orderManager.acceptOrder(${order.order_id})">
                                    <i class="fas fa-check"></i> 接单
                                </button>
                                <button class="btn btn-warning btn-sm" onclick="orderManager.rejectOrder(${order.order_id})">
                                    <i class="fas fa-times"></i> 拒绝
                                </button>
                                <button class="btn btn-info btn-sm" onclick="orderManager.viewOrderDetails(${order.order_id})">
                                    <i class="fas fa-eye"></i> 详情
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="row mt-2">
                        <div class="col-12">
                            <small class="order-details">
                                <i class="fas fa-map-marker-alt"></i> ${order.property_address || '地址信息'}
                                <span class="ms-3">
                                    <i class="fas fa-clock"></i> 创建时间: ${this.formatDateTime(order.created_at)}
                                </span>
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }
    
    getStatusClass(status) {
        const statusMap = {
            1: 'pending',
            2: 'confirmed',
            3: 'paid',
            4: 'completed',
            5: 'cancelled'
        };
        return statusMap[status] || 'pending';
    }
    
    getStatusText(status) {
        const statusMap = {
            1: '待确认',
            2: '已确认',
            3: '已支付',
            4: '已完成',
            5: '已取消'
        };
        return statusMap[status] || '未知';
    }
    
    getPaymentStatusClass(status) {
        const statusMap = {
            1: 'pending',
            2: 'paid',
            3: 'failed'
        };
        return statusMap[status] || 'pending';
    }
    
    getPaymentStatusText(status) {
        const statusMap = {
            1: '待支付',
            2: '已支付',
            3: '支付失败'
        };
        return statusMap[status] || '待支付';
    }
    
    getPriorityClass(priority) {
        const priorityMap = {
            'high': 'priority-high',
            'medium': 'priority-medium',
            'low': 'priority-low'
        };
        return priorityMap[priority] || 'priority-low';
    }
    
    getTimeAgo(dateString) {
        const now = new Date();
        const date = new Date(dateString);
        const diffMs = now - date;
        const diffMins = Math.floor(diffMs / 60000);
        const diffHours = Math.floor(diffMs / 3600000);
        const diffDays = Math.floor(diffMs / 86400000);
        
        if (diffMins < 1) return '刚刚';
        if (diffMins < 60) return `${diffMins}分钟前`;
        if (diffHours < 24) return `${diffHours}小时前`;
        return `${diffDays}天前`;
    }
    
    formatDateTime(dateString) {
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN');
    }
    
    async acceptOrder(orderId) {
        try {
            const response = await fetch('/api/v1/orders/accept', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    order_id: orderId,
                    operator_id: this.currentUser.id,
                    operator_type: 'operator',
                    reason: '接单处理'
                })
            });
            
            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification('接单成功', `订单 ${orderId} 已成功接单`, 'success');
                this.loadOrders(); // 重新加载订单列表
            } else {
                this.showNotification('接单失败', result.msg || '接单操作失败', 'error');
            }
        } catch (error) {
            console.error('接单失败:', error);
            this.showNotification('接单失败', '网络错误，请重试', 'error');
        }
    }
    
    async rejectOrder(orderId) {
        if (!confirm('确定要拒绝这个订单吗？')) {
            return;
        }
        
        try {
            const response = await fetch('/api/v1/orders/reject', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    order_id: orderId,
                    operator_id: this.currentUser.id,
                    operator_type: 'operator',
                    reason: '拒绝接单'
                })
            });
            
            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification('拒绝成功', `订单 ${orderId} 已拒绝`, 'warning');
                this.loadOrders(); // 重新加载订单列表
            } else {
                this.showNotification('拒绝失败', result.msg || '拒绝操作失败', 'error');
            }
        } catch (error) {
            console.error('拒绝失败:', error);
            this.showNotification('拒绝失败', '网络错误，请重试', 'error');
        }
    }
    
    viewOrderDetails(orderId) {
        const order = this.orders.find(o => o.order_id === orderId);
        if (!order) return;
        
        const modal = new bootstrap.Modal(document.getElementById('orderDetailModal'));
        const content = document.getElementById('orderDetailContent');
        
        content.innerHTML = `
            <div class="row">
                <div class="col-md-6">
                    <h6>订单基本信息</h6>
                    <table class="table table-sm">
                        <tr><td>订单号:</td><td>${order.order_no}</td></tr>
                        <tr><td>订单状态:</td><td><span class="badge status-${this.getStatusClass(order.order_status)}">${this.getStatusText(order.order_status)}</span></td></tr>
                        <tr><td>支付状态:</td><td><span class="badge payment-status-${this.getPaymentStatusClass(order.payment_status)}">${this.getPaymentStatusText(order.payment_status)}</span></td></tr>
                        <tr><td>总金额:</td><td>¥${order.total_amount}</td></tr>
                        <tr><td>已支付:</td><td>¥${order.paid_amount}</td></tr>
                        <tr><td>创建时间:</td><td>${this.formatDateTime(order.created_at)}</td></tr>
                        <tr><td>更新时间:</td><td>${this.formatDateTime(order.updated_at)}</td></tr>
                    </table>
                </div>
                <div class="col-md-6">
                    <h6>用户信息</h6>
                    <table class="table table-sm">
                        <tr><td>租客ID:</td><td>${order.tenant_id}</td></tr>
                        <tr><td>租客姓名:</td><td>${order.tenant_name || '未知'}</td></tr>
                        <tr><td>房东ID:</td><td>${order.landlord_id}</td></tr>
                        <tr><td>房东姓名:</td><td>${order.landlord_name || '未知'}</td></tr>
                        <tr><td>物业地址:</td><td>${order.property_address || '未知'}</td></tr>
                    </table>
                </div>
            </div>
        `;
        
        modal.show();
    }
    
    updateConnectionStatus(connected) {
        const statusElement = document.getElementById('connectionStatus');
        if (connected) {
            statusElement.innerHTML = '<i class="fas fa-circle text-success"></i> 已连接';
            statusElement.className = 'alert alert-success';
        } else {
            statusElement.innerHTML = '<i class="fas fa-circle text-danger"></i> 连接断开';
            statusElement.className = 'alert alert-danger';
        }
    }
    
    showNotification(title, message, type = 'info') {
        const notificationContainer = document.getElementById('notificationContainer');
        const alertClass = {
            'success': 'alert-success',
            'error': 'alert-danger',
            'warning': 'alert-warning',
            'info': 'alert-info'
        }[type] || 'alert-info';
        
        const notification = document.createElement('div');
        notification.className = `alert ${alertClass} alert-dismissible fade show notification`;
        notification.innerHTML = `
            <strong>${title}</strong> ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        notificationContainer.appendChild(notification);
        
        // 5秒后自动移除
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 5000);
    }
    
    refreshOrders() {
        this.loadOrders();
        this.showNotification('刷新', '订单列表已刷新', 'info');
    }
    
    toggleAutoRefresh() {
        this.isAutoRefresh = !this.isAutoRefresh;
        const icon = document.getElementById('autoRefreshIcon');
        const text = document.getElementById('autoRefreshText');
        
        if (this.isAutoRefresh) {
            icon.className = 'fas fa-pause';
            text.textContent = '停止自动刷新';
            this.autoRefreshInterval = setInterval(() => {
                this.loadOrders();
            }, 30000); // 30秒刷新一次
        } else {
            icon.className = 'fas fa-play';
            text.textContent = '自动刷新';
            if (this.autoRefreshInterval) {
                clearInterval(this.autoRefreshInterval);
                this.autoRefreshInterval = null;
            }
        }
    }
    
    sortOrders(sortBy) {
        switch (sortBy) {
            case 'time':
                this.filteredOrders.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
                break;
            case 'amount':
                this.filteredOrders.sort((a, b) => b.total_amount - a.total_amount);
                break;
            case 'priority':
                const priorityOrder = { 'high': 3, 'medium': 2, 'low': 1 };
                this.filteredOrders.sort((a, b) => (priorityOrder[b.priority] || 0) - (priorityOrder[a.priority] || 0));
                break;
        }
        this.renderOrders();
    }
    
    showBulkActions() {
        const modal = new bootstrap.Modal(document.getElementById('bulkActionModal'));
        modal.show();
    }
    
    executeBulkAction() {
        const action = document.getElementById('bulkAction').value;
        const remark = document.getElementById('bulkRemark').value;
        
        if (!action) {
            this.showNotification('错误', '请选择要执行的操作', 'error');
            return;
        }
        
        // 这里实现批量操作逻辑
        this.showNotification('批量操作', `已执行${action}操作`, 'success');
        
        const modal = bootstrap.Modal.getInstance(document.getElementById('bulkActionModal'));
        modal.hide();
    }
}

// 全局函数
function refreshOrders() {
    orderManager.refreshOrders();
}

function toggleAutoRefresh() {
    orderManager.toggleAutoRefresh();
}

function showBulkActions() {
    orderManager.showBulkActions();
}

function acceptOrder() {
    // 从模态框获取当前订单ID
    const orderId = document.querySelector('.modal.show').dataset.orderId;
    if (orderId) {
        orderManager.acceptOrder(parseInt(orderId));
    }
}

function rejectOrder() {
    // 从模态框获取当前订单ID
    const orderId = document.querySelector('.modal.show').dataset.orderId;
    if (orderId) {
        orderManager.rejectOrder(parseInt(orderId));
    }
}

// 初始化
let orderManager;
document.addEventListener('DOMContentLoaded', () => {
    orderManager = new OrderAcceptanceManager();
});

